//新增商品


<template>
  <el-container class="add-product-container">
    <el-header class="add-product-header">
      <h2>新增商品</h2>
    </el-header>
    <el-main class="add-product-main">
      <el-form :model="productForm" :rules="rules" ref="productFormRef" label-width="120px" class="product-form">
        <el-form-item label="商品标题" prop="title">
          <el-input v-model="productForm.title" placeholder="请输入商品标题"></el-input>
        </el-form-item>
        <el-form-item label="图片路径" prop="picPaths">
          <el-input v-model="productForm.picPaths" placeholder="请输入商品图片URL"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="productForm.price" :min="0" :precision="2" :step="0.01" placeholder="请输入商品价格"></el-input-number>
        </el-form-item>
        <el-form-item label="商品描述" prop="desc">
          <el-input type="textarea" v-model="productForm.desc" :rows="4" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <!-- 用户ID不再手动输入，将从登录信息中获取 -->
        <el-form-item label="分类ID" prop="categoryid">
          <el-input-number v-model="productForm.categoryid" :min="1" :controls="false" placeholder="请输入分类ID (可选)"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">立即创建</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回商品列表</el-button>
        </el-form-item>
      </el-form>
    </el-main>
  </el-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus';
import { useUserStore } from '@/stores/user'; // 导入用户Store

const router = useRouter();
const productFormRef = ref<FormInstance>();
const userStore = useUserStore(); // 初始化用户Store

// 在组件挂载时检查登录状态
onMounted(() => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再发布商品');
    router.push('/login');
  }
});

const productForm = reactive({
  title: '',
  picPaths: '',
  price: 0,
  desc: '',
  userid: userStore.userId, // 从Store获取用户ID
  categoryid: null as number | null,
});

const rules = reactive<FormRules>({
  title: [{ required: true, message: '请输入商品标题', trigger: 'blur' }],
  picPaths: [{ required: true, message: '请输入图片路径', trigger: 'blur' }],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', message: '价格必须是数字', trigger: 'blur' },
    { validator: (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error('价格必须大于0'));
      } else {
        callback();
      }
    }, trigger: 'blur' }
  ],
  desc: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
});

const submitForm = async () => {
  // 提交前再次检查登录状态
  if (!userStore.isLoggedIn) {
    ElMessage.error('请先登录');
    router.push('/login');
    return;
  }
  
  if (!productFormRef.value) return;
  try {
    const valid = await productFormRef.value.validate();
    if (valid) {
      let loadingInstance: any;
      try {
        loadingInstance = ElLoading.service({ fullscreen: true, text: '正在提交...' });
        const response = await fetch('/api/demo/additem', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            title: productForm.title,
            picPaths: productForm.picPaths,
            price: productForm.price.toFixed(2), // 确保价格是字符串，且保留两位小数
            desc: productForm.desc,
            userid: userStore.userId, // 使用Store中的用户ID
            categoryid: productForm.categoryid,
            typeIndex: 2,
          }),
        });

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
        }

        const result = await response.json();
        ElMessage.success('商品添加成功！');
        console.log('Add product success:', result);
        resetForm(); // 提交成功后清空表单
        router.push('/products'); // 跳转回商品列表页
      } catch (e: any) {
        ElMessage.error('商品添加失败: ' + e.message);
        console.error('Add product failed:', e);
      } finally {
        if (loadingInstance) {
          loadingInstance.close();
        }
      }
    } else {
      ElMessage.error('请检查表单填写，有必填项未填写或格式不正确。');
      // 这里不需要返回 false，因为 validate 已经处理了验证结果
    }
  } catch (error) {
    // validate 方法在验证失败时会 reject Promise，这里可以捕获
    ElMessage.error('表单验证失败，请检查输入。');
    console.error('Form validation failed:', error);
  }
};

const resetForm = () => {
  if (!productFormRef.value) return;
  productFormRef.value.resetFields();
  productForm.userid = parseInt(localStorage.getItem('userid') || '0') || null; // 重置时也从localStorage获取
  productForm.categoryid = null;
};

const goBack = () => {
  router.push('/products');
};
</script>

<style scoped>
.add-product-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.add-product-header {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.add-product-header h2 {
  color: #303133;
  font-size: 28px;
  font-weight: bold;
}

.product-form {
  padding: 20px;
}

.el-input-number {
  width: 100%; /* 让数字输入框宽度与普通输入框一致 */
}
</style>